import { getJsApiTicketServer } from '@/services/otherApi';
import { customeAppId } from '@/src/config';
import Taro from '@tarojs/taro';
import { loadJSSdk } from '../sdk/load-sdk';
import { Platform } from '../sdk/userAgent';

async function share(props) {
  const {
    shareTitle: title,
    h5Logo,
    link = window.location.href.replace(/#.*/, ''),
    hash = window.location.href.replace(/.*?#/, ''),
    description: desc = '',
  } = props;
  const platform = await loadJSSdk();

  console.log('share platform:', { platform, props });

  if (!platform) {
    return;
  }

  const redirectTo = link + (/\?/.test(link) ? '&' : '?') + 'hash=' + encodeURIComponent(hash);

  if (platform === Platform.MINI_PROGRAM) {
    /*wx.miniProgram.postMessage({
      data: {
        type: 'share',
        payload: {
          title,
          imgUrl: minLogo,
          link: redirectTo,
          desc,
        },
      },
    });*/
    return;
  }

  const { content, code, message } = await getJsApiTicketServer({ appId: customeAppId, url: link });
  if (code !== '1') {
    Taro.showToast({
      title: message,
      duration: 1000,
      icon: 'none',
    });
    return Promise.reject();
  }
  console.log('================share config==', { content });

  return new Promise((resolve, reject) => {
    wx.config({
      ...content,
      jsApiList: [
        'updateAppMessageShareData',
        'updateTimelineShareData',
        'onMenuShareTimeline',
        'onMenuShareAppMessage',
        'onMenuShareQQ',
        'onMenuShareWeibo',
        'onMenuShareQZone',
      ],
    });

    wx.ready(() => {
      const shareConfig = {
        title,
        desc,
        link: redirectTo,
        imgUrl: h5Logo,
        success: resolve,
        fail: reject,
        cancel: reject,
      };

      wx.onMenuShareTimeline(shareConfig);
      wx.onMenuShareTimeline(shareConfig);

      wx.updateAppMessageShareData(shareConfig);
      wx.updateTimelineShareData(shareConfig);
    });
  });
}

export { share };
